package com.eding.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eding.constant.MessageConstant;
import com.eding.constant.PasswordConstant;
import com.eding.constant.StatusConstant;
import com.eding.context.BaseContext;
import com.eding.dto.EmployeeDTO;
import com.eding.dto.EmployeeLoginDTO;
import com.eding.dto.EmployeePageQueryDTO;
import com.eding.dto.PasswordEditDTO;
import com.eding.entity.Employee;
import com.eding.exception.AccountLockedException;
import com.eding.exception.AccountNotFoundException;
import com.eding.exception.PasswordErrorException;
import com.eding.mapper.EmployeeMapper;
import com.eding.result.PageResult;
import com.eding.service.EmployeeService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper,Employee> implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        //明文密码进行MD5加密，然后再进行比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    /**
     * 新增员工
     * @param employeeDTO
     * @return
     */
    @Override
    public void saveEmp(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        //属性对拷
        BeanUtils.copyProperties(employeeDTO,employee);
        //设置新增员工账号的状态，1为启用 2为禁用
        employee.setStatus(StatusConstant.ENABLE);
        //设置默认密码并进行md5加密处理
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
        //设置新增员工账号的创建时间与修改时间
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());

        //设置当前账号的创始人与修改人（ID从ThreadLocal中获取）
        employee.setCreateUser(BaseContext.getCurrentId());
        employee.setUpdateUser(BaseContext.getCurrentId());

        employeeMapper.insert(employee);
    }

    /**
     * 员工分页查询
     * @param queryDTO
     * @return
     */
    @Override
    public PageResult getEmpPage(EmployeePageQueryDTO queryDTO) {
        //PageHelper动态拼接limit语句
        PageHelper.startPage(queryDTO.getPage(), queryDTO.getPageSize());
        //分页查询员工信息
        Page<Employee> page = employeeMapper.getEmpPage(queryDTO);
        //从查询出来的page对象中获取需要的参数
        long total = page.getTotal();
        List<Employee> records = page.getResult();
        return new PageResult(total,records);
    }

    /**
     * 启用/禁用 员工账号
     * @param status
     * @param id
     */
    @Override
    public void updateStatus(Integer status, Long id) {
        Employee employee = new Employee();
        employee.setStatus(status);
        employee.setId(id);
        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(BaseContext.getCurrentId());
        employeeMapper.updateById(employee);
    }

    /**
     * 修改员工信息
     * @param employeeDTO
     * @return
     */
    @Override
    public void updateEmp(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO,employee);
        employee.setUpdateTime(LocalDateTime.now());
        //设置当前账号的修改人（ID从ThreadLocal中获取）
        employee.setUpdateUser(BaseContext.getCurrentId());
        employeeMapper.updateById(employee);
    }

    /**
     * 修改员工密码
     * @param passwordEditDTO
     * @return
     */
    @Override
    public boolean editPassword(PasswordEditDTO passwordEditDTO) {
        //先获取当前登录人的id
        Long currentId = BaseContext.getCurrentId();
        //获取传进来的旧密码进行md5加密处理后，与数据库中存放密码进行比对
        String oldPassword = passwordEditDTO.getOldPassword();
        String oldMd5Psd = DigestUtils.md5DigestAsHex(oldPassword.getBytes());
        Employee employee = employeeMapper.selectById(currentId);
        String currentPsd = employee.getPassword();
        //不相等直接返回false
        if (!oldMd5Psd.equals(currentPsd)){
            return false;
        }
        //比对相等则修改为新密码
        String newPassword = passwordEditDTO.getNewPassword();
        String newMd5Psd = DigestUtils.md5DigestAsHex(newPassword.getBytes());
        employee.setPassword(newMd5Psd);
        employeeMapper.updateById(employee);
        return true;
    }
}
